package com.neolix.watch;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.neolix.watch.adapter.MainMenuAdapter;
import com.neolix.watch.bluetooth.BlueToothUtil;
import com.neolix.watch.bluetooth.BluetoothLeService;
import com.neolix.watch.util.Constant;
import com.neolix.watch.util.SharedPreferencesUtil;
import com.neolix.watch.view.MainDisconnectView;
import com.neolix.watch.view.MainTitleView;
import com.neolix.watch.weather.WeatherActivity;

import org.jetbrains.annotations.NotNull;

import static android.view.KeyEvent.KEYCODE_BACK;
import static com.neolix.watch.NeolixApplication.getInstance;

public class MainActivity extends NeolixBaseActivity {

    private boolean isExit;
    private boolean hadCreateGridView;
    private GridView menuGridView;

    private MainTitleView mainTitleView;
    private MainDisconnectView disconnectView;
    private Intent nextIntent;

    public MainActivity() {
        super(R.layout.activity_main);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getInstance().initApp();

        initUi();
        initListener();
        mainTitleView.setCurrentStepValue(SharedPreferencesUtil.getCurrentSteps());
        mainTitleView.setGoalStep(10000);

//        String lastBluetoothDeviceAddress = getLastBluetoothDeviceAddress();
//        if (BlueToothUtil.isEnable() && isNotBlank(lastBluetoothDeviceAddress) && !getInstance().isConnectWatch()) {
//            getInstance().bluetoothLeService.connect(lastBluetoothDeviceAddress);
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshMainTitleView();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
            BlueToothUtil.connectDevice(MainActivity.this);
        } else if (requestCode == Constant.REQUEST_SCAN_BLUETOOTH && resultCode == Activity.RESULT_OK) {
            if (nextIntent != null)
                startActivity(nextIntent);
        } else if (requestCode == Constant.REQUEST_CONNECT_DEVICE && resultCode == Activity.RESULT_OK) {
            if (nextIntent != null)
                startActivity(nextIntent);
        }
    }

    private void initUi() {
        menuGridView = (GridView) findViewById(R.id.menu_gridView);
        mainTitleView = (MainTitleView) findViewById(R.id.main_title_view);
        disconnectView = (MainDisconnectView) findViewById(R.id.bluetooth_disconnect_view);
    }

    private void refreshMainTitleView() {
        boolean isConnected = getInstance().isConnectWatch();
        disconnectView.setVisibility(isConnected ? View.GONE : View.VISIBLE);
        mainTitleView.setVisibility(isConnected ? View.VISIBLE : View.GONE);
    }

    private void initListener() {
        ViewTreeObserver vto = menuGridView.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                if (hadCreateGridView) {
                    return true;
                }
                initGridView(menuGridView);
                hadCreateGridView = true;
                return true;
            }
        });

        disconnectView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextIntent = null;
                BlueToothUtil.connectBluetooth(MainActivity.this);
            }
        });

        mainTitleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goTo(StatisticsActivity.class);
            }
        });
    }

    private void initGridView(GridView gridview) {
        int height = (gridview.getHeight() - 2 * 1) / 3;
        gridview.setAdapter(new MainMenuAdapter(getApplicationContext(), height));
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                switch (position) {
                    case 0:
                        goTo(PayLoginActivity.class);
                        break;
                    case 1:
                        goTo(RemindActivity.class);
                        break;
                    case 2:
                        goTo(WeatherActivity.class);
                        break;
                    case 3:
                        nextIntent = new Intent(getInstance(), WatchStyleActivity.class);
                        if (getInstance().isConnectWatch()) {
                            startActivity(nextIntent);
                        } else {
                            BlueToothUtil.connectBluetooth(MainActivity.this);
                        }
                        break;

                    case 4:
                        nextIntent = new Intent(getInstance(), SearchActivity.class);
                        if (getInstance().isConnectWatch()) {
                            startActivity(nextIntent);
                        } else {
                            BlueToothUtil.connectBluetooth(MainActivity.this);
                        }
                        break;

                    case 5:
                        goTo(SettingActivity.class);
                        break;
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, @NotNull KeyEvent event) {
        if (keyCode != KEYCODE_BACK) {
            return super.onKeyDown(keyCode, event);
        } else {
            exit();
            return true;
        }
    }

    private void exit() {
        if (isExit) {
//            getInstance().exitApp();
//            System.exit(0);
//            finish();
            isExit = false;
            moveTaskToBack(true);
        } else {
            isExit = true;
            Toast.makeText(getApplicationContext(), getString(R.string.tip_exit), Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(0, 500);
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    private void testGreenDao() {
        testDatabase();
    }

    private void testDatabase() {
        //        RunTimeDatabaseHelper runTimeDatabaseHelper = initial(getApplicationContext());
//        InfoDatabaseHelper infoDatabaseHelper;
//        try {
//            infoDatabaseHelper = InfoDatabaseHelper.infoDatabaseHelper(getApplicationContext());
//        } catch (IOException e) {
//            infoDatabaseHelper = null;
//            e.printStackTrace();
//        }
//        runTimeDatabaseHelper.insertUpload();
//        runTimeDatabaseHelper.queryUpload();
//        infoDatabaseHelper.insertCity();
//        infoDatabaseHelper.queryCity();
    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                //TODO 同步时间 && 获取 当天的步数
                refreshMainTitleView();
                Log.i(Constant.BLUETOOTH_TAG, "bluetooth device connected");
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                refreshMainTitleView();
                Log.i(Constant.BLUETOOTH_TAG, "bluetooth device disconnected");
            } else if (Constant.WatchAction.ACTION_WATCH_READ_GET_STEPS.equals(action)) {
                int steps = intent.getIntExtra(BluetoothLeService.EXTRA_DATA, 0);
                mainTitleView.setCurrentStepText(steps);
                SharedPreferencesUtil.setCurrentSteps(steps);
            }
        }
    };

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(Constant.WatchAction.ACTION_WATCH_READ_GET_STEPS);
        return intentFilter;
    }
}
